
__author__ = "furoscame"
__date__ = "29.12.11 23:29"

debug = False

import leonardo_module
import re

class ChessprogramInterfaceError(Exception):
    def __init__(self, value):
         self.value = value
    def __str__(self):
        return repr(self.value)
    pass
pass

class ChessprogramInterface:

    " All methods need to adapt OSA features"

    def __init__(self):
        raise ChessprogramInterfaceError("__init__")
        pass
    pass

    def parse_mosal_message(self, message):
        raise ChessprogramInterfaceError("parse_mosal_message")
        pass
    pass

    def parse_message(self):
        raise ChessprogramInterfaceError("parse_message")
        pass
    pass

    def parse_engine_message(self, message):
        raise ChessprogramInterfaceError("parse_engine_message")
        pass
    pass

    def get_start_cmd(self):
        raise ChessprogramInterfaceError("get_start_cmd")
        pass
    pass

    def get_stop_cmd(self):
        raise ChessprogramInterfaceError("get_stop_cmd")
        pass
    pass

    def get_go_cmd(self):
        raise ChessprogramInterfaceError("get_go_cmd")
        pass
    pass

    def get_interrupt_cmd(self):
        raise ChessprogramInterfaceError("get_interrupt_cmd")
        pass
    pass

    def parse_hint(self, message):
        raise ChessprogramInterfaceError("parse_hint")
        pass
    pass

    def get_cp_level_cmd(self, leo_level_tupel):
        raise ChessprogramInterfaceError("get_cp_level_cmd")
        pass
    pass

    def get_processor_type(self):
        raise ChessprogramInterfaceError("get_processor_type")
        pass
    pass

pass

class WB1Processor(ChessprogramInterfaceError):
    """
    Documentation
    """
    def __init__(self):
        pass
    pass

    def parse_mosal_message(self, message):
        pass
    pass
pass

class WB2Processor(ChessprogramInterfaceError):
    """
    Documentation
    """
    def __init__(self):
        self.leo_module = leonardo_module.LeoModule()
        pass
    pass

    def parse_message(self, message):
        cmd = []
        if message.message == "Setlevel":
            cp_level = self.leo_module.get_level(message.get('level'))
            if debug == True:
                print ("cp_level as tp", cp_level)
            cmd = (self.get_cp_level_cmd(cp_level))
            return cmd
            pass
        elif message.message == "Position":

            r = "setboard" + " " + message.get('fen_str')
            cmd.append(r)
            return cmd
            pass
        elif message.message == "Setup":
            r = "new\n"
            cmd.append(r)
            return cmd
        pass
        return cmd
    pass

    def parse_engine_message(self, message):
        message = message.strip(' ')
        message = re.sub('[\s\t]+', ' ', message)
        result = []
        result.append("unknown")
        string_mode = False
        name = ""

        mes = message.split(" ")
        if debug == True:
            print (mes)
        if mes[0] == 'feature':
            # loop over the features
            for m in mes:
                #print ("m", m)
                m = m.strip('\n\r')

                if string_mode == True:
                    name = name + ' ' + m
                    if '"' in m:
                        string_mode = False
                        print ("WB2 Name", name)
                    continue
                if m == "done=1":
                    result[0] = 'ready'
                    break
                    pass
                elif "myname" in m:
                    m = m.split('=')
                    name = m[1]
                    string_mode = True

        elif mes[0] == "move":
            result[0] = 'move'
            result.append(mes[1])
        elif mes[0] == 'resign':
                result[0] = 'resign'
        elif re.match('[0-9]+\.', mes[0]):
            result[0] = 'move'
            print (mes[2])
            result.append(mes[2])
        elif re.match('[0-9]+', mes[0]):
            if mes[0] != '0':
                result[0] = 'hint'
                result.append(self.parse_hint(message))
        pass

        return result
    pass

    def get_start_cmd(self):
        # make him feel like WB2
        return 'xboard\nprotover 2\nnew\npost\nhard\nics -\n'
        #return "xboard\n"
    pass

    def get_stop_cmd(self):
        return "force\nundo\n"
    pass

    def get_interrupt_cmd(self):
        return "?\n"
    pass
    def get_go_cmd(self):
        return "go\n"
    pass

    def parse_hint(self, message):
        message = re.sub('[\s\t]+', ' ', message)
        mes = message.split(" ")
        hint = WBHint()
        ii = 0
        for m in mes:
            if ii == 0:
                hint.depth = int(mes[0])
            elif ii == 1:
                hint.score = int(mes[1])
                if debug == True:
                    print ("Score", hint.score)
            elif ii == 2 or ii == 3:
                pass
                # time/node nix mit anzufangen
            elif re.match('[0-9]+\.', m):
                #print ("Non m", m)
                # move number
                pass
            else:
                #print ("m:", m)
                if len(m) > 0:
                    hint.pvariante.append(m)
            ii += 1
        return hint
    pass

    def get_cp_level_cmd(self, leo_level_tupel):
        ret = []
        if debug == True:
            print ('leo_level_tupel[0]', leo_level_tupel[0])
        if leo_level_tupel[0] == 'sec':
            r = "st " + leo_level_tupel[1]
            ret.append(r)
            print ("find sec;", ret)
            return ret
            pass
        elif leo_level_tupel[0] == 'ply':
            r = "sd " + leo_level_tupel[1]
            ret.append(r)
            return ret
            pass

        elif leo_level_tupel[0] == 'tour':
            ret = []
            r = "level"
            print ("len tupel",len(leo_level_tupel))
            print ("len tupel",len(leo_level_tupel[1]))
            for l in leo_level_tupel[1]:
                print (l)
                #r = r + " " + l
                for ll in l:
                    r = r + " " + ll # str(l[0]) + " " + l[1] + " " + l[2]
            #ret += "\n"
            ret.append(r)
            if debug == True:
                print ("ret", ret)
            return   ret
            pass
        elif leo_level_tupel[0] == 'mate':
            ret= []
            ret.append("post \n" + "analyze\n")
            if debug == True:
                print ("ret", ret)
            return ret
            pass
        elif leo_level_tupel[0] == 'infinite':
            ret= []
            ret.append("post \n" + "analyze\n")
            if debug == True:
                print ("ret", ret)
            return ret
            pass
        pass
    pass

    def get_processor_type(self):
        return "WB2"
    pass

pass

class UCIProcessor(ChessprogramInterface):
    pass
pass

class WBHint():
    """
    Documentation
    """
    def __init__(self):
        self.depth = 0
        self.score = 0
        self.pvariante = []
        pass
    pass
pass
